package com.senke.aiagent.advisor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.advisor.api.*;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义 Re2 Advisor
 * 可提高大型语言模型的推理能力
 */
@Slf4j
public class Re2Advisor implements CallAroundAdvisor, StreamAroundAdvisor {

    public String getName() {
        return this.getClass().getSimpleName();
    }

    public int getOrder() {
        return 0;
    }

    private AdvisedRequest before(AdvisedRequest request) {
        // 新建一个HashMap，用于存储用户参数，初始内容为request中的advisorParams
        Map<String, Object> advisedUserParams = new HashMap<>(request.advisorParams());
        advisedUserParams.put("re2_input_query", request.userText());
        /*String userText = """
                {re2_input_query}
                Read the request again: {re2_input_query}
                """.replace("{re2_input_query}", request.userText());*/
        // 新建AdvisedRequest对象
        AdvisedRequest newRequest = AdvisedRequest.from(request)
                .userText("""
                        {re2_input_query}
                        Read the question again: {re2_input_query}
                        """)
                //.userText(userText)
                .userParams(advisedUserParams)
                .build();
        return newRequest;
    }


    public String toString() {
        return Re2Advisor.class.getSimpleName();
    }

    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        advisedRequest = this.before(advisedRequest);
        AdvisedResponse advisedResponse = chain.nextAroundCall(advisedRequest);
        return advisedResponse;
    }

    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {
        advisedRequest = this.before(advisedRequest);
        Flux<AdvisedResponse> advisedResponses = chain.nextAroundStream(advisedRequest);
        return advisedResponses;
    }
}
